import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'package:private_journey/services/musicService.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shadcn;
import 'package:signals/signals_flutter.dart';

class MusicPage extends StatefulWidget {
  @override
  State<MusicPage> createState() => _MusicPageState();
}

class _MusicPageState extends State<MusicPage> {
  late final player = Player();
  bool isPlaying = false;
  var qrImg = Signal<QrInfo?>(null);
  Timer? timer;
  String? key;

  @override
  void initState() {
    super.initState();
    this.timer = Timer.periodic(Duration(seconds: 3), (_) async {
      var newKey = await MusicService.createQrKey();
      if (newKey != key) {
        qrImg.value = await MusicService.createLoginQrCode(key!);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Watch((c) {
      return Center(
        child:
            qrImg.value == null
                ? null
                : Builder(
                  builder: (c) {
                    var code = qrImg.value!.qrCode;
                    final String cleanedBase64 = code.replaceAll(
                      RegExp(r'data:image/\w+;base64,'),
                      '',
                    );
                    return Image.memory(base64Decode(cleanedBase64));
                  },
                ),
      );
    });

    // return Container(
    //   child: Center(
    //     child: shadcn.Button(
    //       child: Text(isPlaying ? 'Pause' : 'Play'),
    //       style: shadcn.ButtonStyle.primary(),
    //       onPressed: () async {
    //         if (isPlaying) {
    //           await player.pause();
    //         } else {
    //           await player.open(
    //             Media(
    //               'https://ga-sycdn.kuwo.cn/a89262dd386994c8b4578d5b92785e58/67ff69e9/resource/pay3_v2/436126241/436126241_29_0.1743256352.mp3',
    //             ),
    //           );
    //           await player.play();
    //         }
    //         setState(() {
    //           isPlaying = !isPlaying;
    //         });
    //       },
    //     ),
    //   ),
    // );
  }

  @override
  void dispose() {
    player.dispose();
    super.dispose();
  }
}
